package com.cskaoyan.servlet;

import com.cskaoyan.bean.MarketOrder;
import com.cskaoyan.bean.MarketOrderGoods;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.data.AdminInfoBean;
import com.cskaoyan.bean.vo.OrderDetail;
import com.cskaoyan.bean.vo.UserVo;
import com.cskaoyan.service.*;
import com.cskaoyan.util.*;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Ramsey
 * @date 2023年05月29日 17:08
 */
@WebServlet("/admin/order/*")
public class AdminOrderServlet extends WdBaseServlet {

    AdminOrderService orderService = new AdminOrderServiceimpl();
    OrderGoodsService orderGoodsService = new OrderGoodsServiceimpl();
    UserService userService = new UserServiceImpl();
    //库存的
    GoodsProductService goodsProductService = new GoodsProductServiceimpl();

    @SneakyThrows
    public void list(HttpServletRequest request, HttpServletResponse response) {
        Integer userId = request.getParameter("userId") == null ? null : Integer.parseInt(request.getParameter("userId"));
        String orderSn = request.getParameter("orderSn");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(WdConstant.DEFAULT_DATETIME_PATTERN);
        //LocalDateTime start = LocalDateTime.parse(request.getParameter("start"), formatter);
        //LocalDateTime end = LocalDateTime.parse(request.getParameter("end"), formatter);
        SimpleDateFormat df = new SimpleDateFormat();
        Date start = StringUtil.isEmpty(request.getParameter("start")) ? null : df.parse(request.getParameter("start"));
        Date end = StringUtil.isEmpty(request.getParameter("end")) ? null : df.parse(request.getParameter("end"));
        List<Short> orderStatusArray = new ArrayList<>();
        String[] orderStatusArrays = request.getParameterValues("orderStatusArray");
        if (!ArrayUtil.isEmpty(orderStatusArrays)) {
            orderStatusArray = Arrays.asList(orderStatusArrays).stream().map(Short::valueOf).collect(Collectors.toList());
        }
        Integer page = Integer.parseInt(request.getParameter("page"));
        Integer limit = Integer.parseInt(request.getParameter("limit"));
        String sort = request.getParameter("sort");
        String order = request.getParameter("order");
        CommonData<MarketOrder> commonData = orderService.list(userId, orderSn, start, end, orderStatusArray, page, limit, sort, order);
        ResponseUtil.responseJson(response, BaseRespVo.ok(commonData));
    }

    public BaseRespVo channel(HttpServletRequest request, HttpServletResponse response) {
        List<Map<String, String>> vendors = VendorsProperties.getVendors();
        return BaseRespVo.ok(vendors);
    }

    private BaseRespVo detail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("进入根据orderId查询订单");
        Integer id = Integer.parseInt(request.getParameter("id"));
        MarketOrder marketOrder = orderService.selectById(id);//json需要的order
        List<MarketOrderGoods> marketOrderGoods = orderGoodsService.OrderGoodsSelectByOrderId(id);
        //最后一个只要nickname和avatar（根据什么来找？userId）
        Integer userId = marketOrder.getUserId();
        MarketUser marketUser = userService.selectById(userId);
        //构造一个AdminInfoBean
        UserVo UserInfoBean = new UserVo(marketUser.getNickname(), marketUser.getAvatar());
        //最后封装成OrderDetail
        OrderDetail orderDetail = new OrderDetail(marketOrder, marketOrderGoods, UserInfoBean);
        return BaseRespVo.ok(orderDetail);
    }

    private BaseRespVo refund(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(request.getMethod());
        String jsonStr = request.getReader().readLine();
        System.out.println(jsonStr);
        Map<String, Integer> map = JacksonUtil.read(jsonStr, Map.class);
        Integer orderId = map.get("orderId");
        System.out.println(orderId);
        Integer refundMoney = map.get("refundMoney");
        System.out.println(refundMoney);
        //开启事务
        TransactionUtil.startTransaction();
        //修改订单状态、商品货品增加、返还优惠券(三部曲)

        //修改订单状态
        orderService.changeStatus(orderId);
        //商品货品增加(market_goods_product表)
        //这里一个订单有几件不同的，比如有洗衣液和沐浴露，两个商品的库存都要返还
        List<MarketOrderGoods> marketOrderGoods = orderGoodsService.OrderGoodsSelectByOrderId(orderId);
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            Integer goodsId = marketOrderGood.getGoodsId();//找到商品id
            Short number = marketOrderGood.getNumber();//分别找到每个商品要退款的数量
            String specifications = marketOrderGood.getSpecifications();
            goodsProductService.update(goodsId, number, specifications);//分别传入id和数量再加一个参数 就可以唯一确定一个要改的
        }
        //返还优惠券(coupon_price)
        System.out.println("返回优惠卷");
        //提交事务
        TransactionUtil.commit();

        return BaseRespVo.ok();
    }

    private BaseRespVo ship(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        System.out.println(jsonStr);
        Map<String, Object> map = JacksonUtil.read(jsonStr, Map.class);//{orderId: 477, shipChannel: "EMS", shipSn: "1236"}
        int orderId = (int) map.get("orderId");
        // System.out.println(orderId);
        String shipChannel = (String) map.get("shipChannel");
        // System.out.println(shipChannel);
        String shipSn = (String) map.get("shipSn");
        // System.out.println(shipSn);

        //开启事务
        TransactionUtil.startTransaction();
        SqlSession sqlSession = TransactionUtil.getSqlSession();
        //修改订单状态
        orderService.changeStatusByShip(orderId, shipChannel, shipSn);
        //商品货品减少(market_goods_product表)
        //这里一个订单有几件不同的，比如有洗衣液和沐浴露，两个商品的库存都要返还
        List<MarketOrderGoods> marketOrderGoods = orderGoodsService.OrderGoodsSelectByOrderId(orderId);
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
            Integer goodsId = marketOrderGood.getGoodsId();//找到商品id
            Short number = marketOrderGood.getNumber();//分别找到每个商品要发货的数量
            String specifications = marketOrderGood.getSpecifications();
            goodsProductService.updateByShip(goodsId, number, specifications);//分别传入id和数量再加一个参数 就可以唯一确定一个要改的
        }
        //日志记录(market_log)
        System.out.println("日志记录");
        //提交事务
        TransactionUtil.commit();
        return BaseRespVo.ok();
    }

    private BaseRespVo delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = request.getReader().readLine();
        System.out.println(jsonStr);
        Map<String, Integer> map = JacksonUtil.read(jsonStr, Map.class);//{"orderId":338}
        Integer orderId = map.get("orderId");
        System.out.println(orderId);


        //先判断能不能删（根据orderId找到对应的对象获得状态码判断不行就直接返回fail）如果不符合，事务都没有必要开启
        MarketOrder marketOrder = orderService.selectById(orderId);
        if (marketOrder.getOrderStatus() == 101 || marketOrder.getOrderStatus() == 201 || marketOrder.getOrderStatus() == 202
                || marketOrder.getOrderStatus() == 301) {//未付款、用户取消、申请退款、已发货这几种不能删
            return BaseRespVo.fail(623, "订单不能删除");
        }

        //开启事务
        TransactionUtil.startTransaction();


        //修改订单的deleted字段
        orderService.changeStatusByDelete(orderId);
        //同时修改orderGoods中的deleted字段
        //这里一个订单有几件不同的，比如有洗衣液和沐浴露，两个商品的库存都要修改
        orderGoodsService.OrderGoodsSelectByDelete(orderId);

        //同时完成日志的记录
        System.out.println("日志记录");

        //提交事务
        TransactionUtil.commit();
        return BaseRespVo.ok();
    }


}
